import Taro from '@tarojs/taro'
import queryString from "query-string";
import {WxOpen, wxUserGet, wxUserPut} from "../action/request_action";
import {MuserInfo, IsPublish, Token, UserId, WxWarrant, MLoginInfo,ServicesWechat} from "../constants/enum_consts";

export const showToast = (title = '', icon = 'none',) => {
    Taro.showToast({
        title: title,
        icon: icon,
        duration: 2000,
        mask: false
    })
}

export const hideToast = () => {
    Taro.hideToast();
}

/**
 * 隐藏手机号中间四位
 * @param cellValue
 * @returns {*}
 */
export const hidePhoneNumber = (cellValue) => {
    if (Number(cellValue) && String(cellValue).length === 11) {

        let mobile = String(cellValue)

        let reg = /^(\d{3})\d{4}(\d{4})$/

        return mobile.replace(reg, '$1****$2')

    } else {

        return cellValue

    }
}


/**
 * map转换为url
 * @param params
 */
export const url2param = (params) => {
    let paramsStr = queryString.stringify(params)
    return '?' + paramsStr
}

/*
  * 参数说明：
  * s：要格式化的数字
  * n：保留几位小数
  * */
export const fmoney = (s, n) => {
    if (!s) {
        return 0
    }
    n = n > 0 && n <= 20 ? n : 2;
    s = parseFloat((s + "").replace(/[^\d\.-]/g, "")).toFixed(n) + "";
    var l = s.split(".")[0].split("").reverse(),
        r = s.split(".")[1];
    let t = "";
    for (let i = 0; i < l.length; i++) {
        t += l[i] + ((i + 1) % 3 == 0 && (i + 1) != l.length ? "," : "");
    }
    return t.split("").reverse().join("") + "." + r;
}

export const authorized = () => {
    let that = this;
    Taro.getSetting()
        .then(res => {
            if (res.authSetting["scope.userInfo"]) {
                return true;
            } else {
                throw new Error('没有授权')
            }
        })
        .then(res => {
            return Taro.getUserInfo();
        })
        .then(data => {
            Taro.login({
                success: function (res) {
                    let map = {
                        code: res.code, //--授权码
                        encryptedData: data.encryptedData,
                        iv: data.iv,
                        sessionId: '',
                        userInfo: data.userInfo //微信用户信息
                    }
                    wx_authorize(map, function (data2) {
                        data.sessionKey = data2.data.sessionKey;
                        data.openId = data2.data.openId;
                        data.token = data2.data.token;

                        Taro.setStorageSync('wxAuthorized', data);
                        if (!Taro.getStorageSync('token')) {
                            Taro.setStorageSync('token', data.token);
                        }
                    });
                }
            })
        }).catch(err => {
        console.log(err)
    })
}

export const getUserInfoTool = (data, callback) => {
    let userInfo = data.userInfo;
    if (data.userInfo) {
        let map = {
            encryptedData: data.encryptedData,
            iv: data.iv,
            signature: data.signature,

            headImg: userInfo.avatarUrl,
            city: userInfo.city,
            country: userInfo.country,
            gender: userInfo.gender,
            nickName: userInfo.nickName,
            province: userInfo.province,
            isWxAuthed: true
        };
        Taro.setStorageSync(WxWarrant, data);
        wxUserPut(map, '?id=' + Taro.getStorageSync(UserId), function (data) {
            Taro.setStorageSync(MuserInfo, data)
            callback(data)
        });
    } else {//拒绝
        showToast('拒绝授权,将获取不到相关数据~')
    }
}

export const wxLogin = (map = {}, callback) => {
    Taro.login({
        success: function (res = {}) {
            WxOpen({code: res.code, userId: map.userId, version: map.version}, function (res) {
                Taro.setStorageSync(Token, res.token);
                Taro.setStorageSync(UserId, res.userId);
                Taro.setStorageSync(MuserInfo, res.userInfo);
                Taro.setStorageSync(IsPublish, res.isPublish);
                Taro.setStorageSync(ServicesWechat, res.serviceWeChat);
                Taro.setStorageSync(MLoginInfo, res);
                callback & callback(res)
            });
        }
    })
}

export const getUser = () => {
    wxUserGet({}, '?id=' + Taro.getStorageSync(UserId), function (data) {
        Taro.setStorageSync(MuserInfo, data)
    });
}


/**
 * 将数组array分成长度为subGroupLength的小数组并返回新数组
 * @param array 原始数组
 * @param subGroupLength 每个数组长度
 * @returns {Array}
 */
export const interceptArray = (array, subGroupLength) => {
    if (array && array.length >= 1) {
        let index = 0;
        let newArray = [];
        while (index < array.length) {
            newArray.push(array.slice(index, index += subGroupLength));
        }
        return newArray;
    }
    return array

}

/**
 * 格式化数字成0,000.00
 * @param value
 * @returns {string}
 */
export const formatNumber = (value) => {
    value = (Number(value) / 100).toFixed(2);
    //value=String(value);
    if (isNaN(value)) {
        value = "0.00";
    }
    var result = "";
    var idx = value.indexOf('-');
    if (idx !== -1) {
        value = value.substring(idx + 1);
    }
    ;
    var valueParts = value.split(".");
    var mostSignificationDigit = valueParts[0].length - 1;   // 最高有效数字位，默认为个位
    var intervalOfDigit = 0; 	// 逗号之间的位数
    var digit, countOfSignificationDigit;
    for (var i = valueParts[0].length - 1; i >= 0; i--) {
        digit = valueParts[0][i];
        result = digit + result;
        if (digit != "0") {
            mostSignificationDigit = i;
        }
        if (3 == ++intervalOfDigit) {
            result = "," + result;
            intervalOfDigit = 0;
        }
    }
    if (mostSignificationDigit == -1) {
        result = "0";
    } else {
        countOfSignificationDigit = valueParts[0].length - mostSignificationDigit;
        if (countOfSignificationDigit > 3) {
            result = result.substring(result.length - (countOfSignificationDigit % 3 == 0 ? countOfSignificationDigit / 3 - 1 : countOfSignificationDigit / 3) - countOfSignificationDigit);
        } else {
            result = result.substring(result.length - countOfSignificationDigit);
        }
    }
    if (valueParts.length == 2) {
        result += ".";
        var temp = 2 - valueParts[1].length;	// 是否需要补0
        for (var i = 0; i < temp; i++) {
            valueParts[1] += "0"
        }
        result += valueParts[1].substring(0, 2);
    } else {
        result += ".00";
    }
    if (idx !== -1) {
        return '-' + result;
    }
    return result;
}


/**
 * 计算发表时间, xx分钟以前
 * 调用,参数为时间戳
 */
export const timeAgo = (str) => {
    if (!str) {
        return ''
    }
    let o = new Date(str).getTime();
    var n = new Date().getTime();
    var f = n - o;
    var bs = (f >= 0 ? '前' : '后'); //判断时间点是在当前时间的 之前 还是 之后
    f = Math.abs(f);
    if (f < 6e4) {
        return '刚刚'
    } //小于60秒,刚刚
    if (f < 36e5) {
        return parseInt(f / 6e4) + '分钟' + bs
    } //小于1小时,按分钟
    if (f < 864e5) {
        return parseInt(f / 36e5) + '小时' + bs
    } //小于1天按小时
    if (f < 2592e6) {
        return str.substring(5, str.length - 3);
        // return parseInt(f / 864e5) + '天' + bs
    } //小于1个月(30天),按天数
    if (f < 31536e6) {
        return str.substring(5, str.length - 3);
        // return parseInt(f / 2592e6) + '个月' + bs
    } //小于1年(365天),按月数
    return str.substring(5, str.length - 3);
    // return parseInt(f / 31536e6) + '年' + bs; //大于365天,按年算
}


export default {
    showToast,
    hideToast,
    hidePhoneNumber,
    fmoney,
    authorized,
    getUserInfoTool,
    wxLogin,
    getUser,
    interceptArray,
    formatNumber,
    timeAgo
}


